package juc;

import java.util.Random;
import java.util.concurrent.*;

/**
 * 测试 countDownLatch 两个主线程 await 的情况
 *
 * @author hck
 */
public class TestCountDownLatch {
    private static final int THREAD_COUNT = 5;
    private static final CountDownLatch COUNTER = new CountDownLatch(THREAD_COUNT);

    public static void main(String[] args) {
        ExecutorService executorService = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2));

        executorService.submit(() -> {
            System.out.println("main thread 1 lock:" + Thread.currentThread().getName());
            try {
                COUNTER.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("main thread 1 unlock:" + Thread.currentThread().getName());
        });

        executorService.submit(() -> {
            System.out.println("main thread 2 lock:" + Thread.currentThread().getName());
            try {
                COUNTER.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("main thread 2 unlock:" + Thread.currentThread().getName());
        });


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2));
        for (int i = 0; i < THREAD_COUNT; i++) {
            int finalI = i;
            threadPoolExecutor.submit(() -> {
                Random random = new Random();
                try {
                    Thread.sleep(random.nextInt(100));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("count thread " + finalI + " count down");
                COUNTER.countDown();
            });
        }
    }
}
